<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="w-1/4 xl:w-1/5 left-box">
      <BasicTree
        search
        toolbar
        title="数据库目录"
        :clickRowToExpand="true"
        :treeData="treeData"
        :selectedKeys="selectedTreeKeys"
        expandOnSearch
        :fieldNames="{ key: 'id', title: 'dbName' }"
        @select="handleSelect"
      />
    </div>
    <div class="w-3/4 xl:w-4/5 mr-2 bg-white">
      <BasicTable @register="registerCurrentTable" @expand="expandedRowsChange">
        <template #toolbar>
          <a-button @click="createCode">生成代码</a-button>
          <a-button @click="openTable">打开数据表</a-button>
        </template>
        <template #expandedRowRender="{ record }">
          <a-table
            :columns="innerColumns"
            :data-source="innerDatasource(record.tableName)"
            :pagination="false"
          >
            <template #bodyCell="{ column }">
              <template v-if="column.dataIndex === 'nullable' || column.dataIndex === 'primaryKey'">
                {{ record[column.dataIndex] ? '是' : '否' }}
              </template>
            </template>
          </a-table>
        </template>
      </BasicTable>
    </div>
    <TableModal @register="registerTableModal" />
    <CreateModal @register="registerCreateModal" @success="handleSuccess" />
    <LoadingBox v-if="isLoading" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { BasicTable, useTable, FormSchema, BasicColumn } from '/@/components/Table';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import {
    getDatabaselinkTree,
    getDatabaselinkTable,
    getDatabaselinkMultiTableColumns,
  } from '/@/api/system/databaselink';
  import { batchGeneratorCode } from '/@/api/system/generator';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import TableModal from './components/TableModal.vue';
  import CreateModal from './components/CreateModal.vue';
  import LoadingBox from './components/LoadingBox.vue';

  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '表名',
      dataIndex: 'tableName',
    },
    {
      title: '表备注',
      dataIndex: 'tableComment',
    },
  ];

  const innerColumns: BasicColumn[] = [
    {
      title: '字段名',
      dataIndex: 'column',
      width: 150,
    },
    {
      title: '字段类型',
      dataIndex: 'dataType',
      align: 'center',
    },
    {
      title: '默认值',
      dataIndex: 'columnDefault',
      align: 'center',
    },
    {
      title: '字段长度',
      dataIndex: 'dataLength',
      align: 'center',
    },
    {
      title: '主键',
      dataIndex: 'primaryKey',
      align: 'center',
    },
    {
      title: '允许为空',
      dataIndex: 'nullable',
      align: 'center',
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'tableName',
      label: t('关键字'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];

  const { notification } = useMessage();

  const treeData = ref<TreeItem[]>([]);
  const selectedTreeKeys = ref<string[]>([]);
  const innerData = ref<any[]>([]);
  const isLoading = ref(false);
  const selectDBId = ref('');

  const innerDatasource = (tableName) => {
    const data = innerData.value.filter((item) => {
      if (item && Object.keys(item)) {
        return Object.keys(item)[0] === tableName;
      }
    });
    return data?.length ? data[0][tableName] : [];
  };

  const [registerTableModal, { openModal: openTableModal }] = useModal();
  const [registerCreateModal, { openModal: openCreateModal }] = useModal();

  onMounted(async () => {
    treeData.value = (await getDatabaselinkTree()) as unknown as TreeItem[];
    if (treeData.value.length) {
      let id = treeData.value.length ? treeData.value[0].id : '';
      selectedTreeKeys.value = [id];
      handleSelect([id]);
    }
  });

  const customRow = (record) => {
    return {
      onClick: () => {
        let selectedRowKeys = [...getSelectRowKeys()];
        if (selectedRowKeys.indexOf(record.tableName) >= 0) {
          let index = selectedRowKeys.indexOf(record.tableName);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.tableName);
        }
        setSelectedRowKeys(selectedRowKeys);
      },
    };
  };

  const [registerCurrentTable, { reload: reloadTable, setSelectedRowKeys, getSelectRowKeys }] =
    useTable({
      title: '数据表列表',
      api: getDatabaselinkTable,
      rowKey: 'tableName',
      columns,
      formConfig: {
        rowProps: {
          gutter: 16,
        },
        schemas: searchFormSchema,
      },
      beforeFetch: (params) => {
        return { ...params, id: selectDBId.value };
      },
      useSearchForm: true,
      striped: false,
      showIndexColumn: false,
      isPaginateByDataSource: true,
      rowSelection: {
        type: 'checkbox',
      },
      customRow,
    });

  const handleSelect = async (id) => {
    selectDBId.value = id[0];
    reloadTable();
  };

  const checkInfo = () => {
    if (!selectDBId.value) {
      notification.warning({
        message: 'Tip',
        description: '请选择数据库表',
      });
      return false;
    }
    if (!getSelectRowKeys().length) {
      notification.warning({
        message: 'Tip',
        description: '请选择数据库表',
      });
      return false;
    }
    return true;
  };

  const openTable = () => {
    const isTrue = checkInfo();
    if (!isTrue) return;
    openTableModal(true, {
      databaseId: selectDBId.value,
      tableName: getSelectRowKeys()[getSelectRowKeys().length - 1],
    });
  };

  const createCode = () => {
    const isTrue = checkInfo();
    if (!isTrue) return;
    openCreateModal(true, { databaseId: selectDBId.value, tableName: getSelectRowKeys() });
  };

  async function expandedRowsChange(isOpen, record) {
    if (!isOpen || !!innerData.value?.find((x) => x[record.tableName])) return;
    const tableInfos = await getDatabaselinkMultiTableColumns({
      id: 'master',
      tableNames: record.tableName,
    });
    innerData.value.push(tableInfos);
  }

  const handleSuccess = async (data) => {
    isLoading.value = true;
    data.map(async (item) => {
      await batchGeneratorCode(item);
    });
    isLoading.value = false;
    notification.success({
      message: t('提示'),
      description: '生成代码成功！',
    });
  };
</script>
<style lang="less" scoped>
  .left-box {
    margin-right: 8px;
    overflow: hidden;
    background: #fff;
    height: 100%;
  }

  :deep(.ant-spin-nested-loading) {
    overflow: hidden;
  }
</style>
